<?php
namespace app\deal\Model;
use think\Model;
use think\Db;
use think\Session;
class Order extends Model{
	//获取首页数据
	public static function get_index(){

		$chart = Db::name('bs_price')->order('addtime  DESC')->limit(14)->select();//获取图标需要的数据
		$data['times'] = [];
		$data['prices'] = [];
		$data['config'] = Db::name('bs_config')->field('number_max,multiple')->find();
		$data['current'] = Db::name('bs_price')->order('addtime DESC')->field('price')->find();
		$data['balance'] = self::get_balance();
		//时间更改
		foreach ($chart as $key => $value) {

			$addtime = date('Y-m-d H:i:s',$value['addtime']);

			array_push($data['times'], $addtime);

			array_push($data['prices'], $value['price']);

		}
		// echo json_encode($data);exit;
		return $data;

	}
	//判断是否可以买或者卖
	public static function order_true($type){

		$order = Db::name('bs_order')->where(array('b_or_s'=>$type,'uid'=>self::getUserId(),'types'=>0))->select();

		$order2 = Db::name('bs_order')->where(array('b_or_s'=>$type,'uid'=>self::getUserId(),'types'=>2))->select();

		if($order || $order2){
			
			return false;

		}
		return true;

	}
	//买单下单 
	public static function buy_order($data){

		$config = Db::name('bs_config')->find();

		$times = explode(',',$config['deal_time']);

		if(!in_array(date('w'),$times)){

			return self::return_array(0001,'当前为非交易日',[]);

		}
		$judge_num = self::judge_num($data['num']);
		if(!$judge_num['types']){

			return self::return_array(0001,$judge_num['result'],[]);

		};
		if(!self::order_true(1)){

			return self::return_array(0001,'您有未完成的买入挂单',[]);

		}
		if(!self::verification($data['safepassword'])){

			return self::return_array(0001,'安全密码不正确',[]);

		}
		$pdata['price'] = Db::name('bs_price')->order('addtime DESC')->field('price')->find()['price'];
		$pdata['uid'] = self::getUserId();
		$pdata['b_or_s'] = 1;
		$pdata['money'] = $data['num'];
		$pdata['addtime'] = time();
		if(!Db::name('bs_order')->insert($pdata)){

			return self::return_array(0001,'系统故障，稍后再试',[]);

		}

		return self::return_array(0000,'下单成功，等待卖家匹配!',[]);

	}
	//获取买单列表
	public function get_order($datas){

		$num = $datas['num']?$datas['num']*6:0;

		$data = Db::name('bs_order')->where(array('types'=>0,'b_or_s'=>$datas['b_or_s']))->limit($num,6)->select();

		foreach ($data as $key => $value) {

			$avatar = Db::name('users')->where(array('id'=>$value['uid']))->field('avatar,mobile')->find();

			$data[$key]['avatar'] = $avatar['avatar'];

			$data[$key]['total'] = $value['price']*$value['money'];

			$data[$key]['nickname'] = preg_replace('/(\d{3})\d{5}(\d{3})/', '$1*****$2', $avatar['mobile']);

			$data[$key]['addtime'] = date('Y-m-d H:i:s',$value['addtime']);

		}

		return $data;

	}
	//卖单下单
	public static function sell_order($data){

		$config = Db::name('bs_config')->find();

		$uid = self::getUserId();

		$times = explode(',',$config['deal_time']);

		if(!in_array(date('w'),$times)){

			return self::return_array(0001,'当前为非交易日',[]);

		}
		$judge_num = self::judge_num($data['num']); 
		if(!$judge_num['types']){

			return self::return_array(0001,$judge_num['result'],[]);

		};
		if(!self::order_true(2)){

			return self::return_array(0001,'您有未完成的卖出挂单',[]);

		}
		$receipts = self::verif_receipt(self::getUserId());
		if(!$receipts){

			return self::return_array(0001,'没有可用的收款地址',[]);

		}
		$sellInfo = self::get_sell_info($data['num']);

		if($sellInfo['jian_mey'] > self::get_balance()){

			return self::return_array(0001,'可用资金不足',[]);

		}

		if(!self::verification($data['safepassword'])){

			return self::return_array(0001,'安全密码错误',[]);

		}

		if(!Db::name('users')->where(array('id'=>self::getUserId()))->setInc('money_jifen_freeze',$data['num']) || !Db::name('users')->where(array('id'=>$uid))->setDec('money_benjin',$sellInfo['jian_mey'])){

			return self::return_array(0001,'系统故障，稍后再试',[]);

		}
		$beizhu="卖出流通钱包帐号:".$data['num'].",手续费:".$sellInfo['shouxufei'].",基金结算:".$sellInfo['jijin'].",积分续费:".$sellInfo['fuxiao']."";

		mey_log(3,$uid,2,19,$sellInfo['jian_mey'],self::get_balance(),$beizhu);

		$beizhu3="基金结算:".$sellInfo['jijin'];

		jifen(5,$uid,$sellInfo['jijin'],15,1,$beizhu3);

		$beizhu2="积分结算".$sellInfo['fuxiao'];

		jifen(4,$uid,$sellInfo['fuxiao'],16,1,$beizhu2);

		$pdata['price'] = Db::name('bs_price')->order('addtime DESC')->field('price')->find()['price'];
		$pdata['uid'] = self::getUserId();
		$pdata['b_or_s'] = 2;
		$pdata['money'] = $data['num'];
		$pdata['receipt'] = $receipts;
		$pdata['addtime'] = time();
		if(!Db::name('bs_order')->insert($pdata)){

			return self::return_array(0001,'系统故障，稍后再试',[]);

		}
		
		return self::return_array(0000,'下单成功，等待买家匹配!',[]);

	}
	//用户匹配订单
	public static function buy_order_p($info){

		if(!$info['id'] || !$info['password']){

			return self::return_array(0001,'订单id或安全密码为空！',[]);

		}
		if(!self::verification($info['password'])){

			return self::return_array(0001,'安全密码不正确!',[]);

		}
		$orderInfo = Db::name('bs_order')->where(array('id'=>$info['id']))->find();
		if(!$orderInfo){

			return self::return_array(0001,'订单不存在或已被其他卖家匹配',[]);

		}
		if($orderInfo['uid'] == self::getUserId()){

			return self::return_array(0001,'不能匹配自己发起的订单!',[]);

		} 
		$pdata = array('relative_id'=>self::getUserId(),'types'=>2);

		if($orderInfo['b_or_s'] == 1){
			$uid = self::getUserId();
			$receipts = self::verif_receipt($uid);
			if(!$receipts){

				return self::return_array(0001,'没有可用的收款地址',[]);

			}
			$pdata['receipt'] = $receipts;

			$sellInfo = self::get_sell_info($orderInfo['money']);

			if($sellInfo['jian_mey'] > self::get_balance()){

				return self::return_array(0001,'可用资金不足',[]);

			}

			if(!Db::name('users')->where(array('id'=>$uid))->setInc('money_jifen_freeze',$orderInfo['money']) || !Db::name('users')->where(array('id'=>$uid))->setDec('money_benjin',$sellInfo['jian_mey'])){

				return self::return_array(0001,'系统故障，稍后再试',[]);

			}
			$beizhu="卖出流通钱包帐号:".$orderInfo['money'].",手续费:".$sellInfo['shouxufei'].",基金结算:".$sellInfo['jijin'].",积分续费:".$sellInfo['fuxiao']."";

			mey_log(3,$uid,2,19,$sellInfo['jian_mey'],self::get_balance(),$beizhu);

			$beizhu3="基金结算:".$sellInfo['jijin'];

			jifen(5,$uid,$sellInfo['jijin'],15,1,$beizhu3);

			$beizhu2="积分结算".$sellInfo['fuxiao'];

			jifen(4,$uid,$sellInfo['fuxiao'],16,1,$beizhu2);

		}
		if(!Db::name('bs_order')->where(array('id'=>$info['id']))->update($pdata)){

			return self::return_array(0001,'匹配失败',[]);

		}
		return self::return_array(0000,'匹配成功!',[]);

	}
	//返回的数据格式
	public static function return_array($state,$msg,$data){

		return array('state'=>$state,'msg'=>$msg,'data'=>$data);

	}
	//获取session   userid
	public static function getUserId(){

		session_start();

		return $_SESSION['think']['user']['id'];

	}
	//验证安全密码
	public static function verification($pasword){

		$paswords = Db::name('users')->where(array('id'=>self::getUserId()))->field('paypwd')->find();

		if(md5($pasword) == $paswords['paypwd']){

			return true;

		}

		return false;

	}
	//返回有效的收款地址；
	public static function verif_receipt($userid){

		$receipt = Db::name('bs_receipt')->where(array('uid'=>$userid,'state'=>1,'is_true'=>0))->order('addtime DESC')->find();

		if($receipt){
			return $receipt['id'];
		}else{
			return false;
		}

	}
	//获取当前可交易
	public static function get_balance(){

		$balance = Db::name('users')->where(array('id'=>self::getUserId()))->field('money_benjin')->find();

		return $balance['money_benjin'];

	}
	//获取当前储蓄钱包
	public static function get_jifen(){

		$balance = Db::name('users')->where(array('id'=>self::getUserId()))->field('money_benjin')->find();

		return $balance['money_jifen'];

	}
	//判断交易价格
	public static function judge_num($number){

		$config = Db::name('bs_config')->field('number_max,multiple')->find();

		if(($number % $config['multiple'])){

			return array('types'=>false,'result'=>'交易金额必须为'.$config['multiple'].'的整倍数!');

		}

		if( $number > $config['number_max']){

			return array('types'=>false,'result'=>'单笔最大交易金额为'.$config['number_max'].'!');

		}

		if($number < 0 || !$number){

			return array('types'=>false,'result'=>'只能填写数字');

		}
		
		return array('types'=>true);

	}
	//用户买单列表
	public static function get_user_order($data){

		$num = $data['num']?$data['num']*12:0;

		$datas = Db::name('bs_order')->order('addtime DESC')->where(array('types'=>0,'b_or_s'=>$data['b_or_s']))->limit($num,12)->select();

		return $datas;

	}
	//买单取消
	public static function cancel_buy($id){

		$order = Db::name('bs_order')->where(array('id'=>$id,'types'=>0))->find();

		if(!$order){

			return self::return_array(0001,'订单不存在或已被其他卖家匹配',[]);

		}

		if(!Db::name('bs_order')->where(array('id'=>$id))->update(array('types'=>-1))){

			return self::return_array(0001,'系统故障，稍后再试',[]);

		}
		return self::return_array(0000,'撤销完成!',[]);

	}
	//卖单取消
	public static function cancel_sell($id){

		$order = Db::name('bs_order')->where(array('id'=>$id,'types'=>0))->find();

		if(!$order){

			return self::return_array(0001,'订单不存在或已被其他卖家匹配',[]);

		}
		$uid = self::getUserId();
		$sellInfo = self::get_sell_info($order['money']);

		if(!Db::name('users')->where(array('id'=>$uid))->setDec('money_jifen_freeze',$order['money']) || !Db::name('users')->where(array('id'=>$uid))->setInc('money_benjin',$sellInfo['jian_mey'])){

			return self::return_array(0001,'系统故障，稍后再试',[]);

		}
		$beizhu="卖出流通钱包帐号:".$order['money'].",手续费:".$sellInfo['shouxufei'].",基金结算:".$sellInfo['jijin'].",积分续费:".$sellInfo['fuxiao']."";

		mey_log(3,$uid,1,19,$sellInfo['jian_mey'],self::get_balance(),$beizhu);

		$beizhu3="基金结算:".$sellInfo['jijin'];

		jifen(5,$uid,$sellInfo['jijin'],15,2,$beizhu3);

		$beizhu2="积分结算".$sellInfo['fuxiao'];

		jifen(4,$uid,$sellInfo['fuxiao'],16,2,$beizhu2);

		if(!Db::name('bs_order')->where(array('id'=>$id))->update(array('types'=>-1))){

			return self::return_array(0001,$id,[]);

		}
		return self::return_array(0000,'撤销完成!',[]);

	}
	//获取付款方式页面
	public static function payment_term(){

		$data = Db::name('bs_receipt')->where(array('uid'=>self::getUserId(),'is_true'=>0))->select();

		return $data;

	}
	//添加收款方式
	public static function addterm($data){

		if($data['key'] != 0){

			return self::return_array(0001,'真实姓名或账号为空',[]);

		}
		$datas['types'] = '银行支付';
		$datas['account'] = $data['account'];
		$datas['name'] = $data['realname'];
		$datas['bank'] = $data['bankname'];
		$datas['addtime'] = time();
		$datas['uid'] = self::getUserId();
		$datas['branch'] = $data['bankbranch'];
		if(!Db::name('bs_receipt')->insert($datas)){

			return self::return_array(0001,'系统故障',[]);

		}
		return self::return_array(0000,'添加成功！',[]);

	}
	//获取当前交易订单
	public static function get_user_bsorder($num){

		$uid = self::getUserId();

		$num = $data['num']?$data['num']*6:0;

		$order = Db::name('bs_order')->where( "(`types` IN (1,2) ) and (`uid` = $uid  OR `relative_id` = $uid)")->order('addtime DESC')->limit($num,6)->select();

		foreach ($order as $key => $value) {
			
			$order[$key]['buy'] = Db::name('users')->where(array('id'=>$value['uid']))->field('nickname')->find();

			$order[$key]['sell'] = Db::name('users')->where(array('id'=>$value['relative_id']))->field('nickname')->find();

			if($value['uid'] == $uid ){
				if($value['b_or_s'] == 2){
					if($value['remit_img'] == ''){

						$order[$key]['class'] = 'color-warning';
						$order[$key]['code'] = '等待对方打款';

					}else{

						$order[$key]['class'] = 'color-warning';
						$order[$key]['code'] = '待收款';

					}
				}else{

					if($value['remit_img'] == ''){

						$order[$key]['class'] = 'color-warning';
						$order[$key]['code'] = '待付款';

					}else{

						$order[$key]['class'] = 'color-warning';
						$order[$key]['code'] = '等待对方收款';

					}

				}

			}else{

				if($value['b_or_s'] == 1){
					if($value['remit_img'] == ''){

						$order[$key]['class'] = 'color-warning';
						$order[$key]['code'] = '等待对方打款';

					}else{

						$order[$key]['class'] = 'color-warning';
						$order[$key]['code'] = '待收款';

					}
				}else{

					if($value['remit_img'] == ''){

						$order[$key]['class'] = 'color-warning';
						$order[$key]['code'] = '待付款';

					}else{

						$order[$key]['class'] = 'color-warning';
						$order[$key]['code'] = '等待对方收款';

					}

				}

			}
			if($value['types'] == 1){

				$order[$key]['class'] = 'color-success';
				$order[$key]['code'] = '交易完成';

			}

		}
		return $order;

	}
	//获取订单详细
	public static function get_order_info($id){

		$data = Db::name('bs_order')->where(array('id'=>$id))->find();

		$buyId = $data['b_or_s']==1?$data['uid']:$data['relative_id'];

		$sellId = $data['b_or_s']==2?$data['uid']:$data['relative_id'];

		$data['buy'] = Db::name('users')->where(array('id'=>$buyId))->field('nickname')->find();

		$data['sell'] = Db::name('users')->where(array('id'=>$sellId))->field('nickname,up_userid')->find();

		$data['sell_up'] = Db::name('users')->where(array('id'=>$data['sell']['up_userid']))->field('nickname')->find();

		$data['addtime'] = $data['addtime']?date('Y-m-d H:i:s',$data['addtime']):"";

		$data['amendtime'] = $data['amendtime']?date('Y-m-d H:i:s',$data['amendtime']):"";

		$data['endtime'] = $data['endtime']?date('Y-m-d H:i:s',$data['endtime']):"";

		$data['receipt'] = Db::name('bs_receipt')->where(array('id'=>$data['receipt']))->find();

		$data['usersid'] = self::getUserId();

		return $data;

	}
	//打款截图上传
	public static function affirm_pay($data){

		if(!$data['s']){

			return self::return_array(0001,'付款凭证为空',[]);

		}
		$order = Db::name('bs_order')->where(array('id'=>$data['id'],'types'=>2))->find();
		if(!$order){

			return self::return_array(0001,'订单已取消或已完成',[]);

		}
		if(!Db::name('bs_order')->where(array('id'=>$data['id']))->update(array('remit_img'=>$data['s'],'amendtime'=>time()))){

			return self::return_array(0001,'付款失败',[]);

		}

		return self::return_array(0000,'付款完成',[]);

	}
	//确认收款
	public static function order_receipt($data){

		$order = Db::name('bs_order')->where(array('id'=>$data['id'],'types'=>2))->find();
		if(!$order){

			return self::return_array(0001,'订单已取消或已完成',[]);

		}
		$uid = self::getUserId();

		$buyId = '';
		$sellId = '';
		if($order['b_or_s'] == 1 ){

			$buyId = $order['uid'];

			$sellId = $order['relative_id'];

		}
		if($order['b_or_s'] == 2){

			$buyId = $order['relative_id'];

			$sellId = $order['uid'];

		}
		if(!$buyId){

			return self::return_array(0001,'订单异常！',[]);

		}
		Db::name('users')->where(array('id'=>$sellId))->setDec('money_jifen_freeze',$order['money']);
		Db::name('users')->where(array('id'=>$buyId))->setInc('money_jifen',$order['money']);
		if(!Db::name('bs_order')->where(array('id'=>$order['id']))->update(array('types'=>1,'endtime'=>time()))){

			return self::return_array(0001,'服务器异常',[]);

		}
		$beizhu = "买入到储蓄账户，买入金额:".$order['money'];

		mey_log(1,$buyId,1,20,$order['money'],self::get_jifen(),$beizhu);

		return self::return_array(0000,'收款完成',[]);

	}
	//计算费率基金等
	public static function get_sell_info($money){

		$sys=getsystem();

		$data['fuxiao'] = $money * $sys['shouxufei']/100;

		$data['shouxufei'] = $money * $sys['tixian_xianzhi']/100;

		$data['jijin'] = $money * $sys['tixian_fei']/100;

		$data['jian_mey'] = $money + $data['jijin'] + $data['shouxufei']  + $data['fuxiao'];

		return $data;

		/*$beizhu="会员选择".$licai['qixian']."天理财期限扣除流通钱包".$data['amount']."手续费:".$shouxufei.",基金结算:".$jijin.",积分结算:".$fuxiao;

		mey_log(3,$user['id'],2,12,$jian_mey,$mey,$beizhu);

		$ok=db('users')->where('id',$user['id'])->setField('money_benjin',$mey);

		$beizhu3="基金结算:".$jijin;

		jifen(5,$user['id'],$jijin,15,1,$beizhu3);

		$beizhu2="积分结算".$fuxiao;

		jifen(4,$user['id'],$fuxiao,16,1,$beizhu2);*/

	}
}